package com.yl.chainStore.services.impl.pay

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.chainStore.entity.pay.*
import com.yl.chainStore.mapper.pay.*
import com.yl.chainStore.pojo.vo.warehouse.UpdateItemConfigVo
import com.yl.chainStore.services.pay.ISysCompanyPayItemService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service


@Service
class SysCompanyPayItemServiceImpl(
	private val sysCompanyPayItemTypeMapper: SysCompanyPayItemTypeMapper,
	private val sysCompanyPayItemMapper: SysCompanyPayItemMapper,
	private val sysCompanyReturnVisitConfigMapper: SysCompanyReturnVisitConfigMapper,
	private val sysCompanyPayItemsOperatorConfigMapper: SysCompanyPayItemsOperatorConfigMapper,
	private val payCompanyDeptItemMapper: PayCompanyDeptItemMapper,
	private val payItemCustomerShowRuleMapper: PayItemCustomerShowRuleMapper,
) : ISysCompanyPayItemService {

	companion object {
		private val log = LoggerFactory.getLogger(ISysCompanyPayItemService::class.java)
	}

	override fun updateItem(item: SysCompanyPayItem): ResponseBody {
		log.info("收费项目管理 ==> 修改收费项目 item:{}", item)
		val selectById = sysCompanyPayItemTypeMapper.selectById(item.typeId)
		if(selectById != null){
			item.type = selectById.itemType
		}
		sysCompanyPayItemMapper.updateById(item)
		return returnSuccess()
	}

	override fun itemDetail(itemId: Long, deptId: Long?): SysCompanyPayItem? {
		log.info("收费项目管理 ==> 获取收费项目详情 itemId:{}，deptId:{}", itemId, deptId)

		val item = sysCompanyPayItemMapper.selectById(itemId) ?: return null
		if (item.enabled == 0) {
			return null
		}
		if(deptId != null){
			val deptItems = payCompanyDeptItemMapper.selectList(QueryWrapper<PayCompanyDeptItem?>().eq("item_id",item.id).eq("dept_id",deptId))
			if(deptItems != null && deptItems.size != 0){
				val deptItem = deptItems[0]
				item .deptItem = deptItem
				item.deptRecommendPrice = deptItem.recommendPrice
			}
		}
		item.visitConfig = getVisitConfig(itemId,deptId)
		item.operatorConfig = getOperatorConfig(itemId,deptId)
		return item
	}

	override fun getVisitConfig(itemId: Long, deptId: Long?):List<SysCompanyReturnVisitConfig>?{
		if (deptId != null){
			//获取私有配置，没有的话获取默认配置
			val list = sysCompanyReturnVisitConfigMapper.selectList(
				Wrappers.query<SysCompanyReturnVisitConfig?>()
					.eq("item_id", itemId)
					.eq("dept_id", deptId)
					.orderByAsc("number_of_times")
			)
			return if (list.isEmpty()) {
				log.info("收费项目管理 ==> 获取收费项目详情 未拿到私有回访配置，获取默认配置")

				sysCompanyReturnVisitConfigMapper.selectList(
					Wrappers.query<SysCompanyReturnVisitConfig?>()
						.eq("item_id", itemId)
						.isNull("dept_id")
						.orderByAsc("number_of_times")
				)
			} else {
				list
			}
		}else{
			return sysCompanyReturnVisitConfigMapper.selectList(
				Wrappers.query<SysCompanyReturnVisitConfig?>()
					.eq("item_id", itemId)
					.isNull("dept_id")
					.orderByAsc("number_of_times")
			)
		}
	}

	override fun getOperatorConfig(itemId:Long,deptId: Long?):List<SysCompanyPayItemsOperatorConfig>?{
		if (deptId != null) {
			//获取私有配置，没有的话获取默认配置
			val configList = sysCompanyPayItemsOperatorConfigMapper.selectList(
				Wrappers.query<SysCompanyPayItemsOperatorConfig?>()
					.eq("item_id", itemId)
					.eq("dept_id", deptId)
					.orderByAsc("number_of_times")
			)
			return if (configList.isEmpty()) {
				log.info("收费项目管理 ==> 获取收费项目详情 未拿到私有项目配置，获取默认配置")

				sysCompanyPayItemsOperatorConfigMapper.selectList(
					Wrappers.query<SysCompanyPayItemsOperatorConfig?>()
						.eq("item_id", itemId)
						.isNull("dept_id")
						.orderByAsc("number_of_times")
				)
			} else {
				log.info("收费项目管理 ==> 获取收费项目详情 拿到私有项目配置")
				configList
			}
		}else{
			return sysCompanyPayItemsOperatorConfigMapper.selectList(
				Wrappers.query<SysCompanyPayItemsOperatorConfig?>()
					.eq("item_id", itemId)
					.isNull("dept_id")
					.orderByAsc("number_of_times")
			)
		}
	}

	override fun delItem(itemId: Long): ResponseBody {
		log.info("收费项目管理 ==> 删除收费项目 itemId:{}", itemId)

		val item = sysCompanyPayItemMapper.selectById(itemId) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		item.enabled = 0
		sysCompanyPayItemMapper.updateById(item)
		val cleanOperatorCfg = cleanOperatorCfg(itemId, null,true)
		if (cleanOperatorCfg.code == ErrorCode.SUCCESS.code) {
			return cleanReturnVisitCfg(itemId,null,true)
		}
		return cleanOperatorCfg
	}


	override fun addOperatorCfg(operatorConfig: SysCompanyPayItemsOperatorConfig): ResponseBody {
		log.info("收费项目管理 ==> 添加收费项目配置 operatorConfig:{}", operatorConfig)

		val sysCompanyPayItem = sysCompanyPayItemMapper.selectById(operatorConfig.itemId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"收费项目未找到"
		)
		if (sysCompanyPayItem.enabled == 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "收费项目被删除")
		}
		val queryWrapper = QueryWrapper<SysCompanyPayItemsOperatorConfig>()
		queryWrapper.eq("item_id", operatorConfig.itemId).eq("number_of_times", operatorConfig.numberOfTimes)
		if (operatorConfig.deptId == null) {
			queryWrapper.isNull("item_id")
		} else {
			queryWrapper.eq("item_id", operatorConfig.deptId)
		}
		if (sysCompanyPayItemsOperatorConfigMapper.selectCount(queryWrapper) != 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "项目配置重复")
		}
		sysCompanyPayItemsOperatorConfigMapper.insert(operatorConfig)
		return returnSuccess()

	}


	override fun updateOperatorCfg(operatorConfig: SysCompanyPayItemsOperatorConfig): ResponseBody {
		log.info("收费项目管理 ==> 修改收费项目配置 operatorConfig:{}", operatorConfig)

		sysCompanyPayItemsOperatorConfigMapper.selectById(operatorConfig.id)
			?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		val sysCompanyPayItem = sysCompanyPayItemMapper.selectById(operatorConfig.itemId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"收费项目未找到"
		)
		if (sysCompanyPayItem.enabled == 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "收费项目被删除")
		}
		val queryWrapper = QueryWrapper<SysCompanyPayItemsOperatorConfig>()
		queryWrapper.eq("item_id", operatorConfig.itemId)
			.eq("number_of_times", operatorConfig.numberOfTimes)
			.ne("id", operatorConfig.id)
		if (operatorConfig.deptId == null) {
			queryWrapper.isNull("item_id")
		} else {
			queryWrapper.eq("item_id", operatorConfig.deptId)
		}
		if (sysCompanyPayItemsOperatorConfigMapper.selectCount(queryWrapper) != 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "项目配置重复")
		}
		sysCompanyPayItemsOperatorConfigMapper.updateById(operatorConfig)
		return returnSuccess()
	}

	override fun delOperatorCfg(operatorConfigId: Long): ResponseBody {
		log.info("收费项目管理 ==> 删除收费项目配置 operatorConfigId:{}", operatorConfigId)

		sysCompanyPayItemsOperatorConfigMapper.deleteById(operatorConfigId)
		return returnSuccess()
	}

	override fun cleanOperatorCfg(itemId: Long, deptId: Long?,isAll :Boolean): ResponseBody {
		log.info("收费项目管理 ==> 清除收费项目配置 itemId:{}，deptId:{}，isAll:{}", itemId,deptId,isAll)

		val eq = QueryWrapper<SysCompanyPayItemsOperatorConfig>().eq("item_id", itemId)
		if(!isAll){
			if (deptId == null) {
				eq.isNull("dept_id")
			} else {
				eq.eq("dept_id", deptId)
			}
		}
		sysCompanyPayItemsOperatorConfigMapper.delete(eq)
		return returnSuccess()
	}

	override fun addReturnVisitCfg(returnVisitConfig: SysCompanyReturnVisitConfig): ResponseBody {
		log.info("收费项目管理 ==> 添加收费项目回访配置 returnVisitConfig:{}", returnVisitConfig)

		val sysCompanyPayItem = sysCompanyPayItemMapper.selectById(returnVisitConfig.itemId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"收费项目未找到"
		)
		if (sysCompanyPayItem.enabled == 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "收费项目被删除")
		}
		val queryWrapper = QueryWrapper<SysCompanyReturnVisitConfig>()
		queryWrapper.eq("item_id", returnVisitConfig.itemId).eq("number_of_times", returnVisitConfig.numberOfTimes)
		if (returnVisitConfig.deptId == null) {
			queryWrapper.isNull("item_id")
		} else {
			queryWrapper.eq("item_id", returnVisitConfig.deptId)
		}
		if (sysCompanyReturnVisitConfigMapper.selectCount(queryWrapper) != 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "项目回访配置重复")
		}
		sysCompanyReturnVisitConfigMapper.insert(returnVisitConfig)
		return returnSuccess()

	}

	override fun updateReturnVisitCfg(returnVisitConfig: SysCompanyReturnVisitConfig): ResponseBody {
		log.info("收费项目管理 ==> 修改收费项目回访配置 returnVisitConfig:{}", returnVisitConfig)

		val sysCompanyPayItem = sysCompanyPayItemMapper.selectById(returnVisitConfig.itemId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"收费项目未找到"
		)
		if (sysCompanyPayItem.enabled == 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "收费项目被删除")
		}
		val queryWrapper = QueryWrapper<SysCompanyReturnVisitConfig>()
		queryWrapper.eq("item_id", returnVisitConfig.itemId)
			.eq("number_of_times", returnVisitConfig.numberOfTimes)
			.ne("id",returnVisitConfig.id)
		if (returnVisitConfig.deptId == null) {
			queryWrapper.isNull("item_id")
		} else {
			queryWrapper.eq("item_id", returnVisitConfig.deptId)
		}
		if (sysCompanyReturnVisitConfigMapper.selectCount(queryWrapper) != 0) {
			return returnError(ErrorCode.DATA_SAVE_FAILED, "项目回访配置重复")
		}
		sysCompanyReturnVisitConfigMapper.updateById(returnVisitConfig)
		return returnSuccess()
	}

	override fun delReturnVisitCfg(returnVisitConfigId: Long): ResponseBody {
		log.info("收费项目管理 ==> 删除收费项目配置 returnVisitConfigId:{}", returnVisitConfigId)

		sysCompanyReturnVisitConfigMapper.deleteById(returnVisitConfigId)
		return returnSuccess()
	}

	override fun cleanReturnVisitCfg(itemId: Long,deptId: Long?,isAll :Boolean): ResponseBody {
		log.info("收费项目管理 ==> 清除收费项目配置 itemId:{}，deptId:{}，isAll:{}", itemId,deptId,isAll)

		val eq = QueryWrapper<SysCompanyReturnVisitConfig>().eq("item_id", itemId)
		if(!isAll){
			if (deptId == null) {
				eq.isNull("dept_id")
			} else {
				eq.eq("dept_id", deptId)
			}
		}
		sysCompanyReturnVisitConfigMapper.delete(eq)
		return returnSuccess()
	}

	override fun setPayItemDeptConfig(vo: UpdateItemConfigVo): ResponseBody {
		log.info("部门管理 ==> 服务项目私有设置 vo:{}", vo)
		val item = itemDetail(vo.itemId, vo.deptId) ?: return returnError(
			ErrorCode.OPERATION_DATA_ERROR,
			"项目不存在"
		)
		if (item.enabled == 0) {
			return returnError(
				ErrorCode.OPERATION_DATA_ERROR,
				"项目被删除，请刷新重试"
			)
		}
		val queryWrapper = QueryWrapper<PayCompanyDeptItem>()
		queryWrapper.eq("dept_id", vo.deptId)
			.eq("item_id", vo.itemId)
		var selectOne = payCompanyDeptItemMapper.selectOne(queryWrapper)
		if (selectOne == null) {
			selectOne = PayCompanyDeptItem(
				deptId = vo.deptId ?: getContext().subCompanyId,
				companyId = vo.companyId,
				itemId = vo.itemId
			)
		}
		selectOne.nickname = vo.nickname
		if (vo.warningCount != null) {
			selectOne.warningCount = vo.warningCount!!
		}
		if (vo.highPrice != null) {
			selectOne.highPrice = vo.highPrice!!
		}
		if (vo.warningStatus != null) {
			selectOne.warningStatus = vo.warningStatus!!
		}
		if (vo.recommendPrice != null) {
			selectOne.recommendPrice = vo.recommendPrice!!
		}
		if (vo.canSellMoreWarehouse != null) {
			selectOne.canSellMoreWarehouse = vo.canSellMoreWarehouse!!
		}
		if (vo.showLabel != null) {
			selectOne.canSellMoreWarehouse = vo.canSellMoreWarehouse!!
		}
		if (selectOne.id != 0L) {
			payCompanyDeptItemMapper.updateById(selectOne)
		} else {
			payCompanyDeptItemMapper.insert(selectOne)
		}
		return returnSuccess()
	}

	override fun deptDelPayItem(id: Long,deptId: Long): ResponseBody {
		log.info("部门管理 ==> 部门清除收费项目 id:{}，deptId：{}", id,deptId)
		val item =
			sysCompanyPayItemMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到删除对象，请刷新重试")

		var config = getDeptItemDetail(id,deptId)

		if (item.deptId != null && item.deptId == deptId) {
			delItem(id)
			if (config != null) {
				payCompanyDeptItemMapper.deleteById(config.id)
			}
		} else {
			if (config == null) {
				config = PayCompanyDeptItem(itemId = id, deptId = deptId, useStatus = 0)
				payCompanyDeptItemMapper.insert(config)
			} else {
				config.useStatus = 0
				payCompanyDeptItemMapper.updateById(config)
			}
		}

		return returnSuccess()
	}

	override fun getDeptItemDetail(itemId: Long,deptId: Long):PayCompanyDeptItem?{
		log.info("部门管理 ==> 分院收费项目配置： itemId:{}，deptId：{}", itemId,deptId)
		val list = payCompanyDeptItemMapper.selectList(Wrappers.query<PayCompanyDeptItem?>()
			.eq("dept_id",deptId)
			.eq("item_id",itemId)
		)
		return if(list == null || list.isEmpty()){
			null
		}else{
			list[0]
		}
	}

	override fun setCustomerShowSetting(itemId: Long, subCompanyId:Long, rules: List<PayItemCustomerShowRule>?): ResponseBody {
		payItemCustomerShowRuleMapper.delete(
			Wrappers.query<PayItemCustomerShowRule?>()
				.eq("item_id", itemId)
				.eq("sub_company_id", subCompanyId)
		)
		if(rules != null){
			for(rule in rules){
				payItemCustomerShowRuleMapper.insert(rule)
			}
		}
		return returnSuccess()
	}

	override fun getCustomerShowSetting(itemId: Long, subCompanyId: Long): List<PayItemCustomerShowRule> {
		return payItemCustomerShowRuleMapper.selectList(
			Wrappers.query<PayItemCustomerShowRule?>()
				.eq("item_id", itemId)
				.eq("sub_company_id", subCompanyId)
		)
	}
}
